package com.tianji.learning.service.impl;

import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.DateUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.vo.SignResultVO;
import com.tianji.learning.service.SignRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

import static com.tianji.common.utils.DateUtils.SIGN_DATE_SUFFIX_FORMATTER;
import static com.tianji.learning.constants.RedisConstants.SIGN_RECORD_KEY_PREFIX;

@Service
@Slf4j
@RequiredArgsConstructor
public class SignRecordServiceImpl implements SignRecordService {


    private final StringRedisTemplate redisTemplate;

    private final RabbitMqHelper rabbitMqHelper;

    /**
     * 连续查询签到获取当天积分
     * @return
     */
    @Override
    public SignResultVO addSignRecord() {
       //获取key =SGIN_RECORD_KEY_PREFIX+uid+现在时间yyyymm
        //获取用户id
        Long userId = UserContext.getUser();
        //获取当前时间
        LocalDate now = LocalDate.now();
        //获取当前时间yyyymm格式
        String dateStr = now.format(SIGN_DATE_SUFFIX_FORMATTER);
        //组装key
        String key=SIGN_RECORD_KEY_PREFIX+userId+dateStr;
        //获取当月当天是第几天
        int dayOfMonth = now.getDayOfMonth();
        //获取 bitmap 存入的索引
       int index =dayOfMonth-1;

        //使用redis存入 如果返回true则表示里面存在，否则反之
        Boolean isExist = redisTemplate.opsForValue().setBit(key, index, true);
        if (isExist){
           throw new BizIllegalException("不允许重复签到！");
        }
        //获取连续签到积分
        int integral=consecutiveCheckInPoints(key,dayOfMonth);

        //保存积分到数据库


        //封装vo



        return null;
    }

    private int consecutiveCheckInPoints(String key, int dayOfMonth) {
        return 0;
    }

    @Override
    public Byte[] querySignRecord() {
        return new Byte[0];
    }
}
